#include <signal.h>
#include "app_runner.h"
#include "app_device.h"
#include "app_bt.h"
#include "app_serial.h"
#include "app_mqtt.h"
#include "app_pool.h"
#include "../thirdparty/log.h"

/*设备运行状态变量*/
static int is_running = 1;

/**
 * @brief 结束信号和中止信号共用的回调
 *
 * @param signum 触发回调的信号编号 由操作系统内核传入
 */
void App_runner_exit_handler(int signum)
{
    if (signum == SIGTERM || signum == SIGINT)
    {
        is_running = 0;
    }
}
/**
 * @brief 设备正常工作运行函数
 *
 * @return int 成功返回0 失败返回-1
 */
int App_runner_run(void)
{
    /*1.注册停止信号的回调*/
    /*1.1注册kill信号的回调*/
    signal(SIGTERM, App_runner_exit_handler);
    /*1.2注册ctrl+c中止信号的回调*/
    signal(SIGINT, App_runner_exit_handler);

    /*2.各个模块初始化*/
    /*2.1mqtt初始化*/
    int res = App_mqtt_Init();
    if (res == 0)
    {
        log_info("mqtt init success\n");
    }
    /*2.2线程池初始化*/
    res = App_pool_Init();
    if (res == 0)
    {
        log_info("pthread pool init success\n");
    }
    /*2.3设备初始化*/
    app_dev_t* dev = App_device_Init();
    if (dev != NULL)
    {
        log_info("dev init success\n");
    }
    /*2.4串口初始化*/
    res = App_serial_Init(dev);
    if (res == 0)
    {
        log_info("serial init success\n");
    }
    /*2.5蓝牙初始化*/
    res = App_bt_Init(dev);
    if (res == 0)
    {
        log_info("bt init success\n");
    }
    /*2.6启动设备*/
    res = App_device_Start(dev);
    if (res == 0)
    {
        log_info("dev start success\n");
    }
    
    /*3.阻塞程序,使其一直运行*/
    while (is_running)
    {
        sleep(1);
    }
    
    /*4.程序被指定信号中止运行后,销毁各个模块释放资源*/
    log_info("exit program\n");
    App_mqtt_Deinit();
    App_pool_destroy();
    App_device_destroy(dev);
    
    return 0;
}